package com.debby;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyFileManager extends ListActivity {
    private List<String> items = null;
    private List<String> paths = null;
    /*
     * private String rootPath = "/affairs"; private String curPath =
     * "/affairs";
     */
    private String filepath = "/Tencent/QQfile_recv";
    private String rootPath = "/Tencent/QQfile_recv";
    private String curPath = "/Tencent/QQfile_recv";
    private TextView mPath;

    private final static String TAG = "bb";

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fileselect);
        setRootFile();
        mPath = (TextView) findViewById(R.id.mPath);
        Button buttonConfirm = (Button) findViewById(R.id.buttonConfirm);
        final int flag = getIntent().getIntExtra("flag", 0);
        buttonConfirm.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Intent data = new Intent(MyFileManager.this, MainAcivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("file", curPath);
                data.putExtras(bundle);
                setResult(RESULT_OK, data);
                if (flag != 0) {
                    Intent intent = new Intent();
                    intent.setClassName(MyFileManager.this, "com.javalong.affairs.base.receiver.FileSelectReceiver");
                    intent.putExtra("file", curPath);
                    intent.putExtra("flag", flag);
                    sendBroadcast(intent);
                }
                finish();
            }
        });
        Button buttonCancle = (Button) findViewById(R.id.buttonCancle);
        buttonCancle.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                finish();
            }
        });
        Button buttonPreview = (Button) findViewById(R.id.buttonPreview);
        buttonPreview.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                openImage(curPath);
            }
        });

        File file = new File(rootPath);
        if (!file.exists()) {
            file.mkdir();
        }
        getFileDir(rootPath);
    }

    private void setRootFile() {
        File file = Environment.getExternalStorageDirectory();
        if (file.exists()) {
            String fileString = file.getAbsolutePath() + filepath;
            rootPath = fileString;
            curPath = fileString;
            File f = new File(rootPath);
            if (!f.exists()) {
                f.mkdir();
            }
        }

    }

    private void getFileDir(String filePath) {
        mPath.setText(filePath);
        items = new ArrayList<String>();
        paths = new ArrayList<String>();
        File f = new File(filePath);
        File[] files = f.listFiles();

        if (!filePath.equals(rootPath)) {
            items.add("b1");
            paths.add(rootPath);
            items.add("b2");
            paths.add(f.getParent());
        }
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                items.add(file.getName());
                paths.add(file.getPath());
            }
        }
        setListAdapter(new MyAdapter(this, items, paths));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        File file = new File(paths.get(position));
        //	if (file.isDirectory()) {
        curPath = paths.get(position);
        getFileDir(paths.get(position));
        //} else {
        // openFile(file);
        //	openImage(file);
        //}
    }

    // 判断是否是.png .jpg .jpeg后缀的图片
    private void openImage(String filename) {
        if (filename.endsWith(".png") || filename.endsWith(".jpg")
                || filename.endsWith(".jpeg")) {
            Intent intent = new Intent();
            intent.setClassName(this, "com.javalong.affairs.module.notifything.activity.ImageActivity");
            intent.putExtra("image", filename);
            startActivity(intent);
        } else {
            Toast.makeText(this, "只能预览图片", Toast.LENGTH_SHORT).show();
        }
    }

    private void openFile(File f) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = getMIMEType(f);
        intent.setDataAndType(Uri.fromFile(f), type);
        startActivity(intent);
    }

    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length())
                .toLowerCase();

        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            type = "image";
        } else {
            type = "*";
        }
        type += "/*";
        return type;
    }
}